from flask import Flask, request, jsonify
from flask_cors import CORS
import random
import string
import os
from datetime import datetime, timedelta

app = Flask(__name__)
# 配置 CORS，允许特定来源和方法
CORS(app, resources={
    r"/*": {
        "origins": "http://localhost:5173",  # 明确指定前端来源
        "methods": ["GET", "POST", "OPTIONS"],  # 支持 GET、POST 和 OPTIONS
        "allow_headers": ["Content-Type", "Authorization"],  # 允许的请求头
        "expose_headers": ["Content-Type"],  # 可暴露的响应头
        "supports_credentials": False  # 根据需要启用凭证支持
    }
})

def random_string(length):
    return ''.join(random.choices(string.ascii_letters, k=length))

def random_datetime():
    # 修复：先计算 datetime，再调用 strftime
    dt = datetime.now() - timedelta(days=random.randint(0, 10), hours=random.randint(0, 23), minutes=random.randint(0, 59))
    return dt.strftime('%Y-%m-%d %H:%M:%S')

@app.route('/login', methods=['POST'])
def login():
    data = request.json
    if data['email'] == 'test@example.com' and data['password'] == '123456':
        return jsonify({'success': True})
    return jsonify({'success': False}), 401

@app.route('/get_task_list', methods=['GET'])
def get_task_list():
    page_id = int(request.args.get('page_id', 1))
    env_id = request.args.get('env_id')
    tasks = [
        {
            'task_id': random_string(10),
            'job_id': random_string(10),
            'os': random.choice(['windows', 'linux']),
            'queue_time': random_datetime(),
            'start_time': random_datetime(),
            'end_time': random_datetime(),
            'cpu': 1,
            'memory': random.randint(50, 200),
            'status': random.choice(['waitting', 'runing', 'abort', 'finish']),
            'progress': random.randint(20, 100),
        } for _ in range(10)
    ]
    return jsonify(tasks)

@app.route('/show_task_log', methods=['GET'])
def show_task_log():
    task_id = request.args.get('task_id')
    return jsonify({'log': random_string(50)})

@app.route('/download_task_log', methods=['GET'])
def download_task_log():
    task_id = request.args.get('task_id')
    return jsonify({'log': random_string(100)})

@app.route('/get_job_list', methods=['GET'])
def get_job_list():
    page_id = int(request.args.get('page_id', 1))
    env_id = request.args.get('env_id')
    jobs = [
        {
            'job_id': random_string(10),
            'os': random.choice(['windows', 'linux']),
            'submit_time': random_datetime(),
            'queue_time': random_datetime(),
            'start_time': random_datetime(),
            'end_time': random_datetime(),
            'cpu': 1,
            'memory': random.randint(50, 200),
            'status': random.choice(['waitting', 'runing', 'abort', 'finish']),
            'progress': random.randint(20, 100),
        } for _ in range(10)
    ]
    return jsonify(jobs)

@app.route('/run_job', methods=['POST'])
def run_job():
    job_id = request.json['job_id']
    return jsonify({'success': True})

@app.route('/abort_job', methods=['POST'])
def abort_job():
    job_id = request.json['job_id']
    return jsonify({'success': True})

@app.route('/get_worker_nodes', methods=['GET'])
def get_worker_nodes():
    page_id = int(request.args.get('page_id', 1))
    nodes = [
        {
            'server_id': random_string(10),
            'os': random.choice(['windows', 'linux']),
            'boot_time': random_datetime(),
            'cpu': random.randint(10, 50),
            'memory': random.randint(100, 900),
            'tasks': random.randint(0, 10),
            'version': f'v{random.randint(1, 5)}.{random.randint(0, 9)}',
        } for _ in range(10)
    ]
    return jsonify(nodes)

@app.route('/enable_worker_node', methods=['POST'])
def enable_worker_node():
    worker_id = request.json['worker_id']
    is_enable = request.json['is_enable']
    return jsonify({'success': True})

@app.route('/get_register_url', methods=['GET'])
def get_register_url():
    return jsonify({
        'url': random_string(30),
        'timeout': int((datetime.now() + timedelta(minutes=5)).timestamp())
    })

@app.route('/get_user_list', methods=['GET'])
def get_user_list():
    page_id = int(request.args.get('page_id', 1))
    users = [
        {
            'user_id': random_string(10),
            'bu': random_string(2),
            'email': f'{random_string(5)}@example.com',
            'enable_time': random_datetime(),
            'disable_time': random_datetime(),
            'queue_tasks': random.randint(3, 30),
            'running_tasks': random.randint(3, 30),
            'enabled': random.choice([0, 1]),
        } for _ in range(10)
    ]
    return jsonify(users)

@app.route('/submit_job', methods=['POST'])
def submit_job():
    env_id = request.form['env_id']
    parallel_config = request.files['parallel_config']
    aggregate_config = request.files.get('aggregate_config')
    
    os.makedirs('model_uploaded', exist_ok=True)
    parallel_config.save(os.path.join('model_uploaded', parallel_config.filename))
    if aggregate_config:
        aggregate_config.save(os.path.join('model_uploaded', aggregate_config.filename))
    
    return jsonify({'success': True})

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
